import express, { Router, Request, Response } from 'express';
import { PrismaClient } from '@prisma/client';
import { ResponseHelper } from '../utils/response';
import { authMiddleware } from '../middleware/auth';

const router: Router = express.Router();
const prisma = new PrismaClient();

/**
 * GET /api/tiers
 * 获取所有等级配置（公开接口）
 * 用于前端显示等级表
 */
router.get('/', async (req: Request, res: Response) => {
  try {
    const tiers = await prisma.tierConfig.findMany({
      where: {
        isActive: true,
      },
      orderBy: {
        minInvestment: 'asc', // 按最小投资额从小到大排序
      },
    });

    // 转换 Decimal 类型为数字
    const formattedTiers = tiers.map(tier => ({
      id: tier.id,
      tier: tier.tier,
      name: tier.name,
      dailyRate: Number(tier.dailyRate),
      monthlyRate: Number(tier.monthlyRate),
      annualRate: Number(tier.annualRate),
      minInvestment: Number(tier.minInvestment),
      isActive: tier.isActive,
      createdAt: tier.createdAt,
      updatedAt: tier.updatedAt,
    }));

    return ResponseHelper.success(res, formattedTiers, '등급 구성을 성공적으로 불러왔습니다.');
  } catch (error) {
    console.error('获取等级配置失败:', error);
    return ResponseHelper.error(res, '등급 구성을 불러오지 못했습니다.');
  }
});

/**
 * GET /api/tiers/my-tier
 * 获取当前用户的等级信息
 * 需要登录
 */
router.get('/my-tier', authMiddleware, async (req: Request, res: Response) => {
  try {
    const userId = req.userId;

    if (!userId) {
      return ResponseHelper.error(res, '사용자가 로그인되어 있지 않습니다.', 401);
    }

    const user = await prisma.user.findUnique({
      where: { id: userId },
      select: {
        tier: true,
        stakingInfo: {
          select: {
            stakedAmount: true,
            dailyRewardRate: true,
          },
        },
      },
    });

    if (!user) {
      return ResponseHelper.error(res, '사용자가 존재하지 않습니다.', 404);
    }

    // 获取当前等级配置
    const tierConfig = await prisma.tierConfig.findUnique({
      where: { tier: user.tier },
    });

    if (!tierConfig) {
      return ResponseHelper.error(res, '등급 구성이 존재하지 않습니다.', 404);
    }

    // 转换 Decimal 类型为数字
    const formattedTierConfig = {
      id: tierConfig.id,
      tier: tierConfig.tier,
      name: tierConfig.name,
      dailyRate: Number(tierConfig.dailyRate),
      monthlyRate: Number(tierConfig.monthlyRate),
      annualRate: Number(tierConfig.annualRate),
      minInvestment: Number(tierConfig.minInvestment),
      isActive: tierConfig.isActive,
      createdAt: tierConfig.createdAt,
      updatedAt: tierConfig.updatedAt,
    };

    const formattedStakingInfo = user.stakingInfo ? {
      stakedAmount: Number(user.stakingInfo.stakedAmount),
      dailyRewardRate: Number(user.stakingInfo.dailyRewardRate),
    } : null;

    return ResponseHelper.success(
      res,
      {
        currentTier: user.tier,
        tierConfig: formattedTierConfig,
        stakingInfo: formattedStakingInfo,
      },
      '사용자 등급 정보를 성공적으로 조회했습니다.'
    );
  } catch (error) {
    console.error('获取用户等级信息失败:', error);
    return ResponseHelper.error(res, '사용자 등급 정보를 조회하지 못했습니다.');
  }
});

export default router;
